local voucherId = ARGV[1]
local userId = ARGV[2]
local currentTime = tonumber(ARGV[3])

local stockKey = 'seckill:stock:' .. voucherId
local orderKey = 'seckill:order:' .. voucherId

-- 获取活动信息
local stock = tonumber(redis.call('hget', stockKey, 'stock'))
local startTime = tonumber(redis.call('hget', stockKey, 'start_time'))
local endTime = tonumber(redis.call('hget', stockKey, 'end_time'))

-- 判断活动是否未开始
if currentTime < startTime then
    return 3
end

-- 判断活动是否已结束
if currentTime > endTime then
    return 4
end

-- 判断库存是否充足
if stock <= 0 then
    return 1
end

-- 判断用户是否已经下单
if redis.call('sismember', orderKey, userId) == 1 then
    return 2
end

-- 扣减库存并记录用户
redis.call('hincrby', stockKey, 'stock', -1)
redis.call('sadd', orderKey, userId)

return 0
